package Duoxiancheng;
//银行取款不安全
//synchronized锁共同的资源
public class UnsafeBank {

    public static void main(String[] args) {
        Account account=new Account(100,"结婚基金");
        Drawing zf=new Drawing(account,50,"丈夫");
        Drawing qz=new Drawing(account,100,"妻子");
        zf.setName("丈夫");
        qz.setName("妻子");
        zf.start();
        qz.start();
    }

    //账户
    public static class Account{
        int money;//余额
        String name;//卡名

        public Account(int money, String name) {
            this.money = money;
            this.name = name;
        }
    }

    //银行：模拟取钱
    public static class Drawing extends Thread{
        //账户
        Account account;
        //取走了多少钱
        int drawingMoney;
        //现在卡里的余额
        int nowMoney;

        public Drawing(Account account, int drawingMoney, String name) {
            this.account = account;
            this.drawingMoney = drawingMoney;
            account.name=name;
        }

        //取钱
        @Override
        public void run() {
            synchronized(account){
                //判断有没有钱
                if (account.money-drawingMoney<0){
                    System.out.println(Thread.currentThread().getName()+"钱不够了，取不了了");
                    return;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //结婚基金账户余额
                account.money=account.money-drawingMoney;
                //手里的钱
                nowMoney=nowMoney+drawingMoney;
                System.out.println("结婚基金账户余额"+account.money);
                System.out.println(this.getName()+"手里的钱"+nowMoney);
            }
        }
    }
}
